<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 会员
 *
 */
class User extends CI_Controller {
	function __construct()
	{
		parent::__construct();
		//加载model
		$this->load->model('usermodel');
		$this->uid = $this->usermodel->get_id_by_token($this->input->post('token'));
		//加载ualib
		$this->load->library('ualib');
		//加载url_helper
		$this->load->helper('url');
		//加载表单验证类库
  		$this->load->library('form_validation');
	}
	
	function index()
	{
		$this->myprofile();
	}
	
	/**
	 * 登录
	 *
	 */
	function login()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$_POST['email'] = isset($_POST['email']) ? $_POST['email'] : '';//此处设置时为了防止生成xml报错
		$this->form_validation->set_rules('email', '邮件地址', 'trim|required');
		$this->form_validation->set_rules('password', '密码', 'trim|required');
		$this->form_validation->set_message('required', '%s不能为空');
		
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE){
			$username_error 	= form_error('email');
			$password_error = form_error('password');
			//显示错误信息
			if($username_error)
				echo $this->xmllib->error_xml($username_error);
			elseif ($password_error)
				echo $this->xmllib->error_xml($password_error);
			exit;
		}else{
			//验证数据通过
			//准备执行登录操作
			$username 		= $this->input->post('email');		//邮件、用户名
			$password 		= $this->input->post('password');		//密码
			if($user = $this->usermodel->check_login($username, $password))
			{
				//登录成功session设置
				//$_SESSION['uid'] 	= $user['id'];
				//$_SESSION['name']	= $user['name'];
				//$_SESSION['email']	= $user['email'];
				
				//$this->sessid = session_id();//设置sessionid，并返回手机客户端
				//$this->xmllib->append_xml('PHPSESSID', $this->sessid);
				
				//更新token
				$token = $this->usermodel->update_token($user['id']);
				
				//更新ua信息
				$user_agent = $this->ualib->fetch_array();
				unset($user_agent['ip'], $user_agent['network']);//不需要的字段
				$this->usermodel->update_user($user['id'], $user_agent);
				
				//跳转
				//redirect('/user/index', 'location');
				$this->xmllib->append_xml('token', $token);
				echo $this->xmllib->success_xml("登录成功");
				exit;
			}else{
				//登录失败
				echo $this->xmllib->error_xml("用户名或密码错误，请重新登录");
				exit;
			}
		}
	}
	
	/**
	 * 注册
	 *
	 */
	function register()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$_POST['email'] = isset($_POST['email']) ? $_POST['email'] : '';//此处设置时为了防止生成xml报错
		//字段验证设置
		$this->form_validation->set_rules('email', '邮件地址', 'trim|required|valid_email');
		$this->form_validation->set_rules('password', '密码', 'trim|required|matches[passconf]|min_length[6]|max_length[6]|callback__pass_check|md5');
		$this->form_validation->set_rules('passconf', '确认密码', 'trim|required');
		$this->form_validation->set_message('required', '%s不能为空');
		$this->form_validation->set_message('valid_email', '%s格式不正确');
		$this->form_validation->set_message('min_length', '%s长度不能小于%d');
		$this->form_validation->set_message('max_length', '%s长度不能大于%d');
		$this->form_validation->set_message('matches', '两次输入的密码不一致');
		$this->form_validation->set_message('_pass_check', '密码格式不正确{密码由6位字母或数字组成}');
		
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE){
			$email_error 	= form_error('email');
			$password_error = form_error('password');
			$passconf_error = form_error('passconf');
			//显示错误信息
			if($email_error)
				echo $this->xmllib->error_xml($email_error);
			elseif ($password_error)
				echo $this->xmllib->error_xml($password_error);
			elseif ($passconf_error)
				echo $this->xmllib->error_xml($passconf_error);
			exit;
		}else{
			//验证数据通过
			//准备执行添加操作
			$email 		= $this->input->post('email');		//邮件
			$password 	= $this->input->post('password');	//密码
			if($this->usermodel->check_email($email))
			{
				//此用户已经存在
				echo $this->xmllib->error_xml("邮件地址 {$email} 已经存在，请选择其他合法邮件地址");
				exit;
			}
			//执行插入操作
			$data = array('email' 		=> $email,
							'password'	=> $password,
							'reg_type'	=> 0);
			//$this->db->set('id', '(SELECT UUID())', FALSE);
			if($this->usermodel->insert_user($data)){
				//注册成功
				$userinfo = $this->usermodel->get_userinfo_by_email($email);
				$token = $this->usermodel->update_token($userinfo[0]['id']);//更新token
				//更新ua信息
				$user_agent = $this->ualib->fetch_array();
				unset($user_agent['ip'], $user_agent['network']);//不需要的字段
				$this->usermodel->update_user($userinfo[0]['id'], $user_agent);
				
				$this->xmllib->append_xml('token', $token);
				echo $this->xmllib->success_xml("恭喜您，注册成功");
				exit;
			}else{
				//注册失败
				echo $this->xmllib->error_xml("注册失败，请稍后再试");
				exit;
			}
		}
	}
	
	/**
	 * 合作账号登陆
	 *
	 */
	function loginjoin()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$id 	= $this->input->post('uid');
		$name 	= $this->input->post('name');
		$photo 	= $this->input->post('profile_image');
		$sex 	= $this->input->post('gender');
		$location 	= $this->input->post('location');
		$reg_from 	= $this->input->post('reg_from');
		$data = array('id'			=> $id,
						'name'		=> $name,
						'photo'		=> $photo,
						'sex'		=> $sex,
						'location'	=> $location,
						'reg_type'	=> 1,//合作账号登陆
						'reg_from'	=> $reg_from);
		if($this->usermodel->check_user_by_id($id)){
			//已经存在
			$token = $this->usermodel->update_token($id);//更新token
			//更新ua信息
			$user_agent = $this->ualib->fetch_array();
			unset($user_agent['ip'], $user_agent['network']);//不需要的字段
			$this->usermodel->update_user($id, $user_agent);
			
			$this->xmllib->append_xml('token', $token);
			echo $this->xmllib->success_xml("用户信息更新成功");
			exit;
		}
		if ($this->usermodel->insert_user_join($data)) {
			//注册成功
			$token = $this->usermodel->update_token($id);//更新token
			
			//更新ua信息
			$user_agent = $this->ualib->fetch_array();
			unset($user_agent['ip'], $user_agent['network']);//不需要的字段
			$this->usermodel->update_user($id, $user_agent);
			
			$this->xmllib->append_xml('token', $token);
			echo $this->xmllib->success_xml("恭喜您，注册成功");
			exit;
		}else{
			//注册失败
			echo $this->xmllib->error_xml("注册失败，请稍后再试");
			exit;
		}
	}
	
	/**
	 * 注销
	 *
	 */
	function logout()
	{
		//销毁session
		$this->usermodel->clear_token($this->uid);
		//跳转到登陆页面
		header('Content-type:text/xml');// 向浏览器输出 xml
		echo $this->xmllib->success_xml('成功退出系统');
		exit;
		
	}
	
	/**
	 * 检测邮件地址是否重复
	 *
	 */
	function checkemail()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		//$_POST['email'] = 'andhm@126.com';
		$_POST['email'] = isset($_POST['email']) ? $_POST['email'] : '';//此处设置时为了防止生成xml报错
		//字段验证设置
		$this->form_validation->set_rules('email', '邮件地址', 'trim|required|valid_email');
		$this->form_validation->set_message('required', '请填写%s');
		$this->form_validation->set_message('valid_email', '%s格式不正确');
		$this->form_validation->set_error_delimiters('', '');
		
		if ($this->form_validation->run() == FALSE){
			$email_error 	= form_error('email');
			//显示错误信息
			echo $this->xmllib->error_xml($email_error);
			exit;
		}else{
			//验证通过，则去查询数据库此邮件/昵称是否有重复
			$email = $this->input->post('email');
			if($this->usermodel->check_email($email)){
				//有重复
				echo $this->xmllib->error_xml('邮件地址已经存在');
				exit;
			}else{
				echo $this->xmllib->success_xml('邮件地址有效');
				exit;
			}
		}
	}
	
	/**
	 * 验证昵称
	 *
	 */
	function checkname()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$_POST['name'] = isset($_POST['name']) ? $_POST['name'] : '';//此处设置时为了防止生成xml报错
		//字段验证设置
		$this->form_validation->set_rules('name', '昵称', 'trim|required');
		$this->form_validation->set_message('required', '请填写%s');
		$this->form_validation->set_error_delimiters('', '');
		
		if ($this->form_validation->run() == FALSE){
			$name_error 	= form_error('name');
			//显示错误信息
			echo $this->xmllib->error_xml($name_error);
			exit;
		}else{
			//验证通过，则去查询数据库此昵称/邮件是否有重复
			$name = $this->input->post('name');
			if($this->usermodel->check_user_by_username($name)){
				//有重复
				echo $this->xmllib->error_xml('此昵称已经存在');
				exit;
			}else{
				echo $this->xmllib->success_xml('昵称有效');
				exit;
			}
		}
	}
	
	/**
	 * 修改昵称
	 *
	 */
	function updatename()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$_POST['name'] = isset($_POST['name']) ? $_POST['name'] : '';//此处设置时为了防止生成xml报错
		$this->form_validation->set_rules('name', '昵称', 'trim|required|min_length[3]|max_length[24]|xss_clean');
		$this->form_validation->set_message('required', '%s 不能为空');
		$this->form_validation->set_message('min_length', '%s 长度不能少于%d');
		$this->form_validation->set_message('max_length', '%s 长度不能大于%d');
		
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE){
			$name_error 	= form_error('name');
			//显示错误信息
			echo $this->xmllib->error_xml($name_error);
			exit;
		}else{
			//验证通过，则去查询数据库此昵称/邮件是否有重复(可以和当前用户的name相同)
			$name = $this->input->post('name');
			if($this->usermodel->check_user_by_username($name, $this->uid)){
				//有重复
				echo $this->xmllib->error_xml('此昵称已经存在');
				exit;
			}else{
				//更新昵称
				if($this->usermodel->update_name($this->uid, $name)){
					echo $this->xmllib->success_xml('昵称修改成功');
					exit;
				}else{
					echo $this->xmllib->error_xml('昵称修改失败，请稍候再试');
					exit;
				}
			}
		}
	}
	
	/**
	 * 个人资料
	 *
	 */
	function myprofile()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$userinfo = $this->usermodel->get_userinfo($this->uid);
		if(count($userinfo) > 0){
			$upload_config = $this->config->item('default_img');
			$this->load->library('uploadimglib');//图片路径处理
			//重新赋值，取需要的数据
			$user[0]['id'] 		= $userinfo[0]['id'];
			$user[0]['email']	= $userinfo[0]['email'];
			$user[0]['name']	= $userinfo[0]['name'];
			$user[0]['sex']		= $userinfo[0]['sex'];
			$user[0]['mobile']	= $userinfo[0]['mobile'];
			$user[0]['memo']	= $userinfo[0]['memo'];
			$user[0]['location']	= $userinfo[0]['location'];
			$user[0]['photo']	= $this->uploadimglib->re_user_photo($userinfo[0]['photo'], $userinfo[0]['reg_type']);
			$user[0]['createtime']	= $userinfo[0]['createtime'];
			unset($userinfo);
			//输出最终的xml
			echo $this->xmllib->get_xml($user, array('user'));
			exit;
		}else{
			//结果集为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 查看别人个人资料
	 *
	 */
	function other_myprofile()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$uid = $this->input->post('uid');
		$userinfo = $this->usermodel->get_userinfo($uid);
		if(count($userinfo) > 0){
			$upload_config = $this->config->item('default_img');
			$this->load->library('uploadimglib');//图片路径处理
			//重新赋值，取需要的数据
			$user[0]['id'] 		= $userinfo[0]['id'];
			$user[0]['email']	= $userinfo[0]['email'];
			$user[0]['name']	= $userinfo[0]['name'];
			$user[0]['sex']		= $userinfo[0]['sex'];
			$user[0]['mobile']	= $userinfo[0]['mobile'];
			$user[0]['memo']	= $userinfo[0]['memo'];
			$user[0]['location']	= $userinfo[0]['location'];
			$user[0]['photo']	= $this->uploadimglib->re_user_photo($userinfo[0]['photo'], $userinfo[0]['reg_type']);
			$user[0]['createtime']	= $userinfo[0]['createtime'];
			unset($userinfo);
			//输出最终的xml
			echo $this->xmllib->get_xml($user, array('user'));
			exit;
		}else{
			//结果集为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 更新个人信息
	 *
	 */
	function updateprofile()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$_POST['email'] = isset($_POST['email']) ? $_POST['email'] : '';//此处设置时为了防止生成xml报错
		//字段验证设置
		//$this->form_validation->set_rules('email', '邮件地址', 'trim|required|valid_email');
		$this->form_validation->set_rules('name', '昵称', 'trim|required|min_length[3]|max_length[24]|xss_clean');
		$this->form_validation->set_rules('mobile', '手机号码', 'trim|callback__mobile_check');
		$this->form_validation->set_rules('memo', '签名', 'trim|max_length[120]');
		$this->form_validation->set_rules('location', '地址', 'trim|max_length[120]');

		$this->form_validation->set_message('required', '%s不能为空');
		$this->form_validation->set_message('valid_email', '%s格式不正确');
		$this->form_validation->set_message('min_length', '%s字数不能小于%d');
		$this->form_validation->set_message('max_length', '%s字数不能大于%d');
		$this->form_validation->set_message('_mobile_check', '手机号码格式不正确');
		
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE){
			//$email_error 	= form_error('email');
			$name_error		= form_error('name');
			$mobile_error	= form_error('mobile');
			$memo_error		= form_error('memo');
			$location_error		= form_error('location');
			//显示错误信息
			/*if($email_error)
				echo $this->xmllib->error_xml($email_error);
			else*/
			if ($name_error)
				echo $this->xmllib->error_xml($name_error);
			elseif ($mobile_error)
				echo $this->xmllib->error_xml($mobile_error);
			elseif ($memo_error)
				echo $this->xmllib->error_xml($memo_error);
			elseif ($location_error)
				echo $this->xmllib->error_xml($location_error);
			else 
				echo $this->xmllib->error_xml('更新失败');
			exit;
		}else{
			//$email	= $this->input->post('email');
			$name	= $this->input->post('name');
			$mobile	= $this->input->post('mobile');
			$memo	= $this->input->post('memo');
			$sex	= $this->input->post('sex');
			$location	= $this->input->post('location');
			/*if($this->usermodel->check_email($email, $this->uid))
			{
				//此用户已经存在
				echo $this->xmllib->error_xml("邮件地址 {$email} 已经存在，请选择其他合法邮件地址");
				exit;
			}*/
			if($this->usermodel->check_user_by_username($name, $this->uid))
			{
				//此用户已经存在
				echo $this->xmllib->error_xml("昵称 {$name} 已经存在，请选择其他合法昵称");
				exit;
			}
			
			//执行插入操作
			$data = array(//'email' 		=> $email,
					'name'		=> $name,
					//'mobile'	=> $mobile,
					//'memo'		=> $memo);
							);
			$mobile && $data['mobile'] = $mobile;
			$memo && $data['memo'] = $memo;
			$location && $data['location'] = $location;
			$data['sex'] = in_array($sex, array(1,2)) ? $sex : 0;
			if($this->usermodel->update_user($this->uid, $data)){
				//更新成功
				echo $this->xmllib->success_xml("更新个人资料成功");
				exit;
			}else{
				//更新失败
				echo $this->xmllib->error_xml("更新个人资料失败，请稍后再试");
				exit;
			}
			
		}
	}
	
	/**
	 * 更新图像
	 *
	 */
	function updatephoto()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$photo = isset($_FILES['photo']) ? $_FILES['photo'] : array();
		if(empty($photo) || $photo['size']==0 || empty($photo['name'])){
			echo $this->xmllib->error_xml('请选择要上传的图像');
			exit;
		}
		unset($photo);//释放
		//加载图片上传处理类库
		$this->load->library('uploadimglib');
		//加载配置文件
		$this->config->load('upload');
		$this->config->load('image_lib');
		//从配置文件中取值
		$upload_config = $this->config->item('default_img');
		$image_config = $this->config->item('default_img_resize');
		
		//做点改动，设置图片的上传路径
		$upload_config['upload_path'] = $this->uid . '/profileimg';
		
		if($path = $this->uploadimglib->upload_image($upload_config, 'photo', $upload_config['default_path'])){
			if($dest_path = $this->uploadimglib->resize_image($image_config, $path)){
				//处理路径，只要相对路径即可
				$dest_path = substr($dest_path, strpos($dest_path, 'images/'.$this->uid));
				$user = $this->usermodel->get_userinfo($this->uid);
				if($this->usermodel->update_photo($this->uid, $dest_path)){
					//更新图像成功
					//图像处理成功，删除硬盘上原始图片
					$this->uploadimglib->remove_image($user[0]['photo'], 1, $upload_config['default_path']); 
					unset($user);
					
					echo $this->xmllib->success_xml('更新图像成功');
					exit;
				}else{
					//更新图像失败
					//处理失败就删除上传成功的图片
					$this->uploadimglib->remove_image($dest_path, 1, $upload_config['default_path']);
					echo $this->xmllib->error_xml('更新图像失败，请稍候再试');
					exit;
				}
			}else{
				//resize图像失败
				//处理失败就删除上传成功的图片
				$this->uploadimglib->remove_image($dest_path, 0, $upload_config['default_path']);
				echo $this->xmllib->error_xml('个人图像处理失败，请稍候再试');
				exit;
			}
		}else{
			//更新图像失败
			echo $this->xmllib->error_xml('个人图像更新失败，请稍候再试');
			exit;
		}
	}
	
	/**
	 * 个人主页
	 *
	 */
	function mypage()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$_count_arr = $this->_mypage($this->uid);
		$user_agent = $this->ualib->fetch_array();//ua信息
		$user_model = isset($user_agent['user_model']) ? trim($user_agent['user_model']) : '';
		$this->xmllib->append_xml('user_model', $user_model);
		echo $this->xmllib->get_xml($_count_arr);
		exit;
	}
	
	/**
	 * 查看别人的个人主页
	 *
	 */
	function other_mypage()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$uid = $this->input->post('uid');
		$_count_arr = $this->_mypage($uid);
		//查看别人的软件安装数量
		$this->load->model('appmodel');
		$appinstall_count = $this->appmodel->get_apps_install_count($uid, 1);
		$appinstall_count = $appinstall_count['count'];
		$_count_arr['appinstall_count'] = $appinstall_count;
		unset($_count_arr['message_count']);//无法查看别人的消息的
		echo $this->xmllib->get_xml($_count_arr);
		exit;
	}
	
	/**
	 * 相同机型用户
	 *
	 */
	function same_usermodel()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$uid = $this->input->post('uid');
		if($uid==false) $uid=$this->uid;//没有传递uid，默认是当前用户
		$this->dblib->set_query_limit();//分页
		$result = array();
		$this->db->select('a.id, a.name, a.photo as photo, a.sex, a.memo, a.user_model, a.reg_type')
    			 ->from('user as a')
    			 ->join('user as b', 'a.user_model=b.user_model')
    			 ->where(array('b.id' => $uid, 'a.id <>' => $this->uid));
    	$query = $this->db->get();
    	if ($query->num_rows() > 0) {
			//如果有结果集
			$this->load->library('uploadimglib');
			$result = $query->result_array();
			//设置photo路径
			foreach ($result as $k=>$v){
				$result[$k]['photo'] = $this->uploadimglib->re_user_photo($v['photo'], $v['reg_type']);
			}
			//输出最终的xml
			echo $this->xmllib->get_xml($result, array('user'), 'users');
			exit;
		}else{
			//结果集为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	//获取主页信息，（包括查看别人的主页）
	function _mypage($uid='')
	{
		$attentions_count = $this->_get_count('attentions', array('uid' => $uid));
		$album_count = $this->_get_count('album', array('uid' => $uid, 'isdel' => 0));
		$fans_count = $this->_get_count('fans',array('uid' => $uid));
		$collection_count = $this->_get_count('collection', array('uid' => $uid));
		$message_count = $this->_get_count('message', array('uid' => $uid));
		$active_count = $this->_get_count('active', array('uid' => $uid));
		$_count_arr = array('attentions_count' 	=> $attentions_count,
							'album_count'		=> $album_count,
							'fans_count'		=> $fans_count,
							'collection_count'	=> $collection_count,
							'message_count'		=> $message_count,
							'active_count'		=> $active_count);
		return $_count_arr;
	}
	
	//密码强度检测
	public function _pass_check($password='')
	{
		/*return preg_match('/^\w{6,16}$/', $password) && 
				!preg_match('/^[a-z]+$/i', $password) && 
				!preg_match('/^[0-9]+$/i', $password) && 
				!preg_match('/^\_+$/i', $password);*/
		return preg_match('/^[a-zA-Z0-9]{6}$/', $password)==true;//6位数字或者字母设置
	}
	
	//手机号码验证
	public function _mobile_check($mobile='')
	{
		if(!empty($mobile)){
			return preg_match('/^1(3|5|8)[0-9]{9}$/', $mobile) == true;
		}
		return true;
	}
	
	// 获取主页各项数目
	public function _get_count($table, $where = array()){
		$this->db->select('count(*) as count')
				->from($table)->where($where);
		$query = $this->db->get();
		$row = $query->row_array();
		return $row['count'];
	}
}

/* End of file user.php */
/* Location: ./application/controllers/user.php */